<?php 

class PhotogalleryModel extends BaseModel
{
	private $table;
	private $table_items;
	
	/**
	 * Hold an instance of the class
	 * @var CommonPageModel
	 */
	private static $_instance = null;
	
	/**
	 * A private constructor
	 * Prevents direct creation of object
	 */
	private function __construct()
	{
		$this->_init();
		$this->table = TABLE_PREFIX . "photogallery";
		$this->table_items = TABLE_PREFIX . "photogallery_items";
	}

	/**
	 * The singleton method
	 * @return CommonPageModel
	 */
	public static function getInstance()
	{
		if (!self::$_instance instanceof self)
			self::$_instance = new self;

		return self::$_instance;
	}
	
	/**
	 * Returns info by id menu.
	 * 
	 * @param $id_menu
	 * @return array|DibiRow
	 */
	public function getInfo($id_menu){

		$info = dibi::query("SELECT * FROM ".$this->table." WHERE id_menu = %i", $id_menu, " ORDER BY id_photogallery DESC")->fetchAll();
		
		return $info;
	}
	
	public function saveGallery($id_menu, $name){
			
			$menu = SystemModel::getInstance()->getMenuItemByName($id_menu);
		
			$arr = array(
						"id_menu" => $menu[0]["id_menu"],
						"date" => new DateTime(),
						"title" => $name,
						"seo_title" => String::webalize($name)
						);
			
			return dibi::query("INSERT INTO ".$this->table, $arr);
	}
	
	public function getPictures($id_photogallery){
		
		return dibi::query("SELECT * FROM ".$this->table_items." LEFT JOIN ". TABLE_FILES." USING(id_file) WHERE id_photogallery = %i", $id_photogallery)->fetchAll();
	}
	
	public function updateGallery($id, $args){
		
		$args["seo_title"] = String::webalize($args["title"]);
		
		return dibi::query("UPDATE ".$this->table." SET ", $args, "WHERE id_photogallery = %i", $id);
	}
	
	public function getPhotogalleryInfo($id_photogallery){
		
		return dibi::query("SELECT * FROM " . $this->table . " WHERE id_photogallery = %i", $id_photogallery)->fetch();
	}
	
	public function getPhotogalleryInfoByTitle($seo_title){
		return dibi::query("SELECT * FROM " . $this->table . " WHERE seo_title = %s", $seo_title)->fetch();
	}
	
	public function deleteGalleryPictures($id){
		
		return dibi::query("DELETE FROM " . $this->table_items . " WHERE id_photogallery = %i", $id);
	}
	
	/**
	 * Saves gallery pictures and info.
	 * @param $args
	 * @return void
	 */
	public function saveGalleryPictures($args){
		
		return dibi::query("INSERT INTO ".$this->table_items." %ex", $args);
		
	}
	
	public function deletePhotogallery($id){
		
		return dibi::delete($this->table)
				->where("id_photogallery = %i", $id)
				->execute();
	}
	
	public function getMainPhoto($id_photogallery){
		
		return dibi::query("SELECT * FROM " . $this->table_items . " JOIN ". TABLE_FILES." USING(id_file) WHERE hlavni = 1 AND id_photogallery = %i", $id_photogallery)->fetch();
	}
	
}

?>